<template>
	<view class="user">
		<view class="user-form">
			<uni-forms ref="form" :model="formData" :rules="rules">
				<uni-forms-item name="username">
					<uni-easyinput prefixIcon="person-filled" v-model="formData.username" focus placeholder="请输入用户名"
						:styles="inputStyles" />
				</uni-forms-item>
			</uni-forms>
			<button class="btn-submit" @click="handleSave">保存</button>
		</view>
	</view>
</template>

<script>
	import updateInfoApi from '../../../api/avatar/avatar.js'
	import {
		mapState,
		mapMutations
	} from 'vuex'
	export default {
		data() {
			return {
				formData: {
					username: '',
				},
				inputStyles: {
					borderColor: '#8be627',
				},
				// 校验规则
				rules: {
					username: {
						rules: [{
							required: true,
							errorMessage: '用户名不能为空'
						}]
					},
				},
			}
		},
		computed: {
			...mapState('login', ['userInfo'])
		},
		methods: {
			...mapMutations('login', {
				'setUserInfo': 'SET_USERINFO'
			}),
			handleSave() {
				this.$refs['form'].validate().then((res) => {
					let param = {
						userId: this.userInfo.userId,
						...this.formData
					}
					updateInfoApi.updateUserName(param).then(res => {
						if (res.code == 200 && Object.keys(res.info).length != 0) {
							this.setUserInfo(res.info)
							uni.setStorageSync('userInfo', JSON.stringify(res.info))
							if (getCurrentPages().length > 1) {
								uni.navigateBack()
							} else {
								uni.navigateTo({
									url: '/pages/avatar/setting'
								})
							}
						}
					})
				}).catch(err => {
					console.log('err', err);
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.user {
		width: 100vw;
		height: 100vh;
		background-size: cover;
		background-color: $uni-bg-color;

		.user-form {
			text-align: center;
			padding: 20rpx;

			.btn-submit {
				background-color: $uni-primary;
				color: $uni-white;
			}
		}

	}
</style>